package byx.container.annotation.util;

import byx.container.annotation.annotation.Order;

import java.lang.reflect.AnnotatedElement;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class OrderUtils {
    public static <T extends AnnotatedElement> List<T> sort(Collection<T> elements) {
        return elements.stream()
                .sorted(OrderUtils.comparator())
                .collect(Collectors.toList());
    }

    public static <T extends AnnotatedElement> Comparator<T> comparator() {
        return Comparator.comparingInt(OrderUtils::getOrder);
    }

    public static int getOrder(AnnotatedElement element) {
        if (element.isAnnotationPresent(Order.class)) {
            return element.getAnnotation(Order.class).value();
        }
        return 1;
    }
}
